package edu.scu.declaresys.web.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;

import edu.scu.declaresys.config.IAttrName;
import edu.scu.declaresys.service.ServiceFactory;
import edu.scu.declaresys.service.intr.IMsgClassService;
import edu.scu.declaresys.vo.MsgClass;
import edu.scu.declaresys.web.ABaseAction;

public class MsgClassAction extends ABaseAction implements
		ModelDriven<MsgClass>
{
	private static final long	serialVersionUID	= 1792444991866917901L;
	
	private IMsgClassService service = ServiceFactory.createMsgClassService();
	
	private MsgClass vo = new MsgClass();
	
	//
	// action
	//
	public String msgClassAdd() throws Exception
	{
		if(vo.getName() == null)
		{
			throw new Exception("类别名称不能为空");
		}
		if(service.findClassByName(vo.getName()) != null)
		{
			throw new Exception("类别已经存在");
		}
		vo.setId(service.addClass(vo));
		request.setAttribute(IAttrName.CLASS_VO, vo);
		return Action.SUCCESS;
	}
	
	public String msgClassDelete() throws Exception
	{
		if(vo.getId() == null)
		{
			throw new Exception("未指定ID");
		}
		else
		{
			//TODO:未检查当前类别下是否还有信息
			service.deleteClass(vo.getId());
		}
		return Action.SUCCESS;
	}
	
	public String msgClassModify() throws Exception
	{
		if(vo.getName() != null)
		{
			if(vo.getId() == null)
			{
				throw new Exception("未指定类别");
			}
			else if(service.findClassByName(vo.getName()) != null)
			{
				throw new Exception("该类别已经存在！");
			}
			else if(service.findClass(vo.getId()) == null)
			{
				throw new Exception("该类别不存在");
			}
			service.modifyClass(vo);
		}
		return Action.SUCCESS;
	}
	
	public String msgClassList() throws Exception
	{
		request.setAttribute(IAttrName.CLASS_LIST, service.findClassList());
		return Action.SUCCESS;
	}
	
	public String msgClassDetail() throws Exception
	{
		if(vo.getId() != null)
		{
			throw new Exception("未指定类别！");
		}
		vo = service.findClass(vo.getId());
		request.setAttribute(IAttrName.CLASS_VO, vo);
		return Action.SUCCESS;
	}
	
	public String msgClassCheckDuplicate() throws Exception
	{
		boolean isDuplicate = (service.findClassByName(vo.getName()) != null);
		request.setAttribute(IAttrName.CLASS_DUPLICATE_FLAG, isDuplicate);
		return Action.SUCCESS;
	}

	
	//
	// Getters and Setters.
	//
	
	@Override
	public MsgClass getModel()
	{
		return vo;
	}

	public MsgClass getMsgClass()
	{
		return vo;
	}

	public void setMsgClass(MsgClass msgClass)
	{
		this.vo = msgClass;
	}
}
